﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Configuration;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using AutoFacWrapper;
using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.AdvancedAPIs.TemplateMessage;
using Senparc.Weixin.MP.CommonAPIs;
using ZLWeb.WebApiControllers;
using ZLWeb.WebApiEntity.EasyUse;
using ZLWeb.WebApiRepository.InterFace;

[assembly: WebActivator.PreApplicationStartMethod(typeof(AttributeRoutingHttpConfig), "Start")]

namespace ZLWeb.WebApiApplication
{
    // 注意: 有关启用 IIS6 或 IIS7 经典模式的说明，
    // 请访问 http://go.microsoft.com/?LinkId=9394801

    public class WebApiApplication : HttpApplication
    {
        protected void Application_Start()
        {
            Bootstrapper.Run();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalConfiguration.Configuration.Filters);
            //RouteConfig.RegisterRoutes(RouteTable.Routes);
            TaskFactory tf = new TaskFactory();
            //Task task = tf.StartNew(TaskMethod);
        }

        /// <summary>
        /// 后台线程轮询充值和消费状态
        /// </summary>
        private void TaskMethod()
        {
            var paymentRepository = ClassFactory.GetInstance<IPaymentRepository>();
            while (true)
            {
                try
                {
                    Thread.Sleep(1000);
                    IEnumerable<WxMsg> msgs = paymentRepository.GetWxMsg();
                    foreach (var wxmsgitem in msgs)
                    {
                        if (wxmsgitem.msgform == 1)
                        {
                            object dy = GetPayMsgTemplate(wxmsgitem.msgcontent);
                            SendTemplate(wxmsgitem.msgwxopenid, TestTemplateId, dy);
                        }
                        if (wxmsgitem.msgform == 3)
                        {
                            object dy = GetChargeMsgTemplate(wxmsgitem.msgcontent);
                            SendTemplate(wxmsgitem.msgwxopenid, TestTemplateId, dy);
                        }
                    }
                }
                catch (Exception ex)
                {

                }
            }
        }

        private object GetChargeMsgTemplate(string msgcontent)
        {
            string[] msgs = msgcontent.Split('|');
            if (msgs.Count() != 4) return null;
            var testData = new
            {
                PersonName = new TemplateDataItem(msgs[0]),
                ChargeDate = new TemplateDataItem(msgs[1]),
                ChargeAmount = new TemplateDataItem(msgs[2]),
                ChargeLeft = new TemplateDataItem(msgs[3]),
            };
            return testData;
        }

        private object GetPayMsgTemplate(string msgcontent)
        {
            string[] msgs = msgcontent.Split('|');
            if (msgs.Count() != 6) return null;
            var testData = new 
            {
                PersonName = new TemplateDataItem(msgs[0]),
                PPAmount = new TemplateDataItem(msgs[1]),
                Bonuspoint = new TemplateDataItem(msgs[2]),
                Shop = new TemplateDataItem(msgs[3]),
                AmountLeft = new TemplateDataItem(msgs[4]),
                CurrentBonus = new TemplateDataItem(msgs[5]),
            };
            return testData;
        }

        public static readonly string appId = WebConfigurationManager.AppSettings["WeixinAppId"];//与微信公众账号后台的AppId设置保持一致，区分大小写。
        public static readonly string secret = WebConfigurationManager.AppSettings["WeixinAppSecret"];//与微信公众账号后台的AppId设置保持一致，区分大小写。
        public static readonly string TestTemplateId = WebConfigurationManager.AppSettings["TestTemplateId"];//与微信公众账号后台的AppId设置保持一致，区分大小写。
        public static readonly string PayTemplateId = WebConfigurationManager.AppSettings["PayTemplateId"];//与微信公众账号后台的AppId设置保持一致，区分大小写。
        public static readonly string ChargeTemplateId = WebConfigurationManager.AppSettings["ChargeTemplateId"];//与微信公众账号后台的AppId设置保持一致，区分大小写。

        private SendTemplateMessageResult SendTemplate(string openId,string TemplateId, object dy)
        {
            AccessTokenContainer.Register(appId, secret);
            var accessToken = AccessTokenContainer.GetAccessToken(appId);
            var testData = new //TestTemplateData()
            {
                pay = new TemplateDataItem("【测试】您好，审核通过。"),
                address = new TemplateDataItem(openId),
                time = new TemplateDataItem(DateTime.Now.ToString()),
                remark = new TemplateDataItem("更详细信息，请到Senparc.Weixin SDK官方网站（http://weixin.senparc.com）查看！")
            };
            var result = TemplateApi.SendTemplateMessage(accessToken, openId, TemplateId, "#FF0000", "", testData);
            return result;
        }
    }
}